import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import {
  CreateArticleDto,
  DeleteArticleDto,
  EditArticleDto,
  FindKeyArticleDto,
  FindManyDto,
} from './dto/article.dto';
import { PrismaService } from '../prisma/prisma.service';
import { pipeline } from 'stream/promises';
import * as fs from 'fs';
import { ConfigService } from '@nestjs/config';
import * as path from 'path';

@Injectable()
export class ArticleService {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly configService: ConfigService,
  ) { }

  async create(cad: CreateArticleDto) {
    // 检查类别是否已存在
    const findOne = await this.prismaService.article.findFirst({
      where: { title: cad.title, userId: cad.userId },
    });
    if (findOne) {
      throw new HttpException('名称已存在', HttpStatus.BAD_REQUEST);
    }
    try {
      await this.prismaService.article.create({ data: { ...cad } });
      return '文章添加成功';
    } catch (error) {
      throw new HttpException('文章添加失败', HttpStatus.BAD_REQUEST);
    }
  }

  async findMany(fmd: FindManyDto) {
    try {
      const res = await this.prismaService.article.findMany({
        where: {
          userId: fmd.userId,
          subCategoryId: fmd.subCategoryId,
          isDelete: false,
        },
      });
      return res;
    } catch (error) {
      throw new HttpException('文章查找失败', HttpStatus.BAD_REQUEST);
    }
  }

  async findKeyArticle(fkad: FindKeyArticleDto) {
    // parentCatId首页第二类
    const { parentCatId, userId } = fkad;
    try {
      const catList = await this.prismaService.subCategory.findMany({
        where: { parentCatId, userId },
      });
      const subCatIds = catList
        ?.filter((cat) => cat.parentId)
        ?.map((cat) => cat.id);
      const articleList = await this.prismaService.article.findMany({
        where: {
          subCategoryId: { in: subCatIds },
          userId,
          isDelete: false,
          NOT: { keyLevel: '' },
        },
      });
      return articleList.sort((a: any, b: any) => b.keyLevel - a.keyLevel);
    } catch (error) {
      throw new HttpException('重点文章查找失败', HttpStatus.BAD_REQUEST);
    }
  }

  async edit(ead: EditArticleDto) {
    try {
      await this.prismaService.article.update({
        where: { id: ead.id },
        data: { ...ead },
      });
      return '文章编辑成功';
    } catch (error) {
      throw new HttpException('文章编辑失败', HttpStatus.BAD_REQUEST);
    }
  }

  async delete(dad: DeleteArticleDto) {
    try {
      await this.prismaService.article.delete({ where: { id: dad.id } });
      return '文章删除成功';
    } catch (error) {
      throw new HttpException('文章删除失败', HttpStatus.BAD_REQUEST);
    }
  }

  /**
   * 上传单个文件
   * @param req FastifyRequest
   * @returns 上传后的文件路径
   */
  async uploadSingleFile(req: any) {
    const fileObj = req.multipartFile
    if (!fileObj || !fileObj.file) {
      throw new HttpException('未上传文件', HttpStatus.BAD_REQUEST);
    }
    const fileStream = fileObj.file;
    // filename加个时间戳
    const ext = path.extname(fileObj.filename);
    const baseName = path.basename(fileObj.filename, ext);
    const timestamp = Date.now();
    const filename = `${baseName}_${timestamp}${ext}`;
    // const filename = fileObj.filename;
    const uploadDir = this.configService.get('UPLOAD_DIR') ?? '/upload';
    const savePath = `./public${uploadDir}/${filename}`;

    // 确保目录存在
    const dir = path.dirname(savePath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }

    // 用 stream/promises 的 pipeline
    await pipeline(fileStream, fs.createWriteStream(savePath));

    return { path: `/static${uploadDir}/${filename}` };
  }
}
